<template>
  <div class="edit">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品{{ type }}</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加/修改表单 -->
    <el-form
      ref="form"
      :model="form"
      label-width="80px"
      style="margin-top: 20px"
    >
      <el-form-item label="一级分类" prop="first_cateid">
        <el-select v-model="form.first_cateid" placeholder="请选择">
          <el-option
            v-for="item in cateList"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="二级分类" prop="second_cateid">
        <el-select v-model="form.second_cateid" placeholder="请选择">
          <el-option
            v-for="item in sec_cateList"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称" style="width: 400px">
        <el-input v-model="form.goodsname"></el-input>
      </el-form-item>

      <el-form-item label="商品价格" style="width: 400px" type="number">
        <el-input v-model="form.price"></el-input>
      </el-form-item>

      <el-form-item label="市场价格" style="width: 400px" type="number">
        <el-input v-model="form.market_price"></el-input>
      </el-form-item>

      <el-form-item label="图片">
        <!--<div v-show="isShow"> 这里需要使用 v-show 来判断图片显示与否。若是分类添加则不显示图片，若是分类编辑则需要将原数据的图片显示出来
                  <img width="150px" height="150px" :src="dialogImageUrl" alt="" /> 编辑某一项数据时，要先把保存好的图片给它展示出来。只需要双向绑定一下src即可。只是添加的话 dialogImageUrl是空的，不会影响
              </div> 试了一下还是不要显示图片了，效果不是很好-->
        <el-upload
          action="#"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :auto-upload="false"
          :on-change="handleChange"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="商品规格" prop="specsid">
        <el-select
          v-model="form.specsid"
          placeholder="请选择"
          @change="specsChange(form.specsid)"
        >
          <el-option
            v-for="item in specsList"
            :key="item.id"
            :label="item.specsname"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="规格属性" prop="specsattr">
        <el-select v-model="form.specsattr" placeholder="请选择" multiple>
          <!--multiple 多选-->
          <el-option
            v-for="attr in sec_specsList"
            :key="attr"
            :label="attr"
            :value="attr"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否新品">
        <el-switch
          v-model="form.isnew"
          :active-value="1"
          :inactive-value="0"
          active-color="green"
          inactive-color="red"
        ></el-switch>
      </el-form-item>

      <el-form-item label="是否热卖">
        <el-switch
          v-model="form.ishot"
          :active-value="1"
          :inactive-value="0"
          active-color="green"
          inactive-color="red"
        ></el-switch>
      </el-form-item>

      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-color="green"
          inactive-color="red"
        ></el-switch>
      </el-form-item>

      <el-form-item label="商品描述">
        <div id="editor"></div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import E from "wangeditor";
export default {
  name: "edit",
  data() {
    return {
      type: "添加",
      form: {
        first_cateid: "", // 一级菜单
        second_cateid: "", // 二级菜单
        goodsname: "", // 商品名称
        price: "", // 商品价格
        market_price: "", // 市场价格
        description: "", // 商品描述
        specsid: "", // 规格名称
        specsattr: "", // 规格属性
        isnew: "", // 是否新品
        ishot: "", // 是否热卖
        status: "", // 状态
      },
      img: [{ name: "", url: "" }], // 图片（文件，一般用于二级分类）将img单独拎出来。解决编辑之后若是没有改变图片，随后返回主页面图片消失的问题
      cateList: [],
      specsList: [],
      attrsList: [""],
      editor: null,
      dialogImageUrl: "",
      dialogVisible: false,
      //isShow: false
    };
  },
  computed: {
    // 分类一级与二级菜单联动
    sec_cateList() {
      if (this.cateList.length > 0) {
        let arr = this.cateList.filter(
          (item) => item.id == this.form.first_cateid
        );
        if (arr[0]) {
          return arr[0].children;
        } else {
          return [];
        }
      } else {
        return [];
      }
    },
    // 规格一级与二级菜单联动
    sec_specsList() {
      if (this.specsList.length > 0) {
        const arr = this.specsList.filter(
          (item) => item.id === this.form.specsid
        );
        if (arr[0]) {
          return arr[0].attrs;
        } else {
          return [];
        }
      } else {
        return [];
      }
    },
  },
  mounted() {
    let id = this.$route.params.id;
    if (id) {
      this.type = "编辑";
      this.img = [{ name: "1", url: "" }]; // 解决编辑之后若是没有改变图片，随后返回主页面图片消失的问题
      this.getGoodsInfo(id);
    }

    // 获得商品分类信息
    this.getCateList();

    // 获得商品规格信息
    this.getSpecsList();

    // 初始化富文本编辑器
    this.editor = new E("#editor");
    this.editor.create();
  },
  methods: {
    // 上传图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleChange(file) {
      //console.log(file);
      this.img = file.raw; // 此处变为this.img 而不是this.form.img了
    },

    // 获得一级商品信息
    getCateList() {
      this.$axios
        .get("/api/catelist", { params: { istree: 1 } })
        .then((result) => {
          this.cateList = result.data.list;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getSpecsList() {
      this.$axios
        .get("/api/specslist")
        .then((result) => {
          //console.log(result);
          this.specsList = result.data.list;
          //console.log(this.specsList);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 规格属性
    specsChange(id) {
      this.$axios
        .get("/api/specsinfo", { params: { id } })
        .then((result) => {
          //console.log(result);
          this.attrsList = result.data.list[0].attrs;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 获得需要编辑的信息（一条）
    getGoodsInfo(id) {
      this.$axios
        .get("/api/goodsinfo", { params: { id } })
        .then((result) => {
          this.form = result.data.list;
          this.editor.txt.html(this.form.description);
          this.form.specsattr = this.form.specsattr.split(","); // 这里我使用split，实现的效果还可以
          this.img = this.form.img; // 解决编辑之后若是没有改变图片，随后返回主页面图片消失的问题
          //this.form.specsattr = ''
          /*this.form.specsattr = this.form.specsattr.map((item) => {
            return { value: item };
          });*/
          //console.log(item)
          console.log(result);
          console.log(this.form.specsattr);
        })
        .catch((err) => {
          console.log(err);
        });
    },

    onSubmit() {
      //获得form表单，然后进行验证
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 深拷贝
          let str = JSON.stringify(this.form); // 使用json序列化图片会出现冲突，所以要把图片img单独拎出来
          let data = JSON.parse(str);

          data.description = this.editor.txt.html();

          // 如果type是编辑，则把接口地址改为编辑的接口
          let url = "/api/goodsadd";
          if (this.type === "编辑") {
            data.id = this.$route.params.id;
            url = "/api/goodsedit";
          }

          // 因为要上传的图片是文件，所以要把上传的数据转为formData 表单提交
          let formData = new FormData();
          for (let key in data) {
            formData.append(key, data[key]);
          }
          formData.append("img", this.img); // 单独添加img

          this.$axios
            .post(url, formData)
            .then((result) => {
              console.log(result);
              if (result.data.code === 200) {
                this.$router.push("/goods");
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
#editor {
  width: 800px;
  height: 400px;
}
</style>
